package org.spacetrader.web;

import java.util.Properties;

import javax.naming.NamingException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;

import org.hibernate.HibernateException;
import org.hibernate.transaction.TransactionManagerLookup;
import org.hibernate.util.NamingHelper;

public class PortableTransactionManagerLookup implements TransactionManagerLookup {
	/**
	 * {@inheritDoc}
	 */
	@Override
	public TransactionManager getTransactionManager(Properties props)
			throws HibernateException {
		String [] attempts = {"java:appserver/TransactionManager",
				"java:comp/TransactionManager",
				"java:/TransactionManager"};
		
		TransactionManager result = null;
		
		for (String attempt : attempts) {
			try {
				result = (TransactionManager) NamingHelper
						.getInitialContext(props).lookup(attempt);
				
				return result;
			}
			catch (NamingException e) {
			}			
		}
		
		throw new HibernateException("Could not find any supported" +
				" TransactionManager JNDI name");
	}

	@Override
	public Object getTransactionIdentifier(Transaction transaction) {
		return transaction;
	}

	@Override
	public String getUserTransactionName() {
		return "UserTransaction";
	}
}
